<template>
  <div class="upload-container">
    <el-upload
      class="upload-demo"
      drag
      multiple
      :auto-upload="false"
      :on-change="handleFileChange"
      :file-list="fileList"
      :limit="5"
      accept=".pdf,.docx,.txt,.jpg,.png"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件至此或 <em>点击选择文件</em></div>
      <template #tip>
        <div class="el-upload__tip">
          支持扩展名：.pdf .docx .txt .jpg .png（单个文件不超过10MB）
        </div>
      </template>
    </el-upload>

    <el-button 
      type="primary" 
      @click="submitUpload"
      :disabled="fileList.length === 0"
    >
      上传文件（{{ fileList.length }}）
    </el-button>

    <el-table :data="fileslists" style="width: 100%; margin-top: 20px">
      <el-table-column prop="originalName" label="文件名" />
      <el-table-column prop="size" label="大小" :formatter="formatSize" />
      <el-table-column prop="uploadTime" label="上传时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="downloadFile(scope.row)">
            下载
          </el-button>     
           <el-button link type="danger"  @click="deleteFile(scope.row) ">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import type { UploadFile, UploadFiles } from 'element-plus'
import { ElMessage } from 'element-plus';
import { reFileList,reDleteFile } from '@/api/file'
import { color } from 'echarts';
interface FileItem {
  id: number
  originalName: string
  storedName: string
  size: number
  uploadTime: string
  downloadUrl: string
    // 添加文件类型字段
    type?: string
}

const fileList = ref<UploadFile[]>([])
const uploadedFiles = ref<FileItem[]>([])
let fileslists = ref()

// 处理文件选择
const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  fileList.value = files
}

// 格式化文件大小
const formatSize = (row: any) => {
  const size = row.size
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`
  return `${(size / 1024 / 1024).toFixed(2)} MB`
}

// 提交上传
const submitUpload = async () => {
  const formData = new FormData()
  fileList.value.forEach(file => {
    formData.append('files', file.raw!)
  })

  try {
    const response = await axios.post('http://localhost:8080/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Token':localStorage.getItem('TOKEN')
      }
    })
    

    fileList.value = []
    ElMessage.success('上传成功')
    getFilelist()
  } catch (error) {
    ElMessage.error('上传失败')
  }
  
}


// 下载文件
const downloadFile = async (file: FileItem) => {
  try {
    const response = await axios.get(file.downloadUrl, {
      responseType: 'blob',
      headers: {
        'Token': localStorage.getItem('TOKEN')
      }
    })

    // 创建Blob对象并生成下载链接
    const blob = new Blob([response.data], { type: response.headers['content-type'] })
    const downloadUrl = window.URL.createObjectURL(blob)
    
    // 创建隐藏的可下载链接
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = file.originalName
    
    // 兼容性处理：不同浏览器的下载方式
    if (typeof link.download === 'undefined') {
      link.setAttribute('target', '_blank')
    }

    document.body.appendChild(link)
    link.click()
    
    // 清理资源
    window.URL.revokeObjectURL(downloadUrl)
    document.body.removeChild(link)

    ElMessage.success('文件下载已开始')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('文件下载失败，请检查网络或权限')
    
    // 处理特定错误状态
    if (axios.isAxiosError(error)) {
      if (error.response?.status === 401) {
        ElMessage.warning('登录已过期，请重新登录')
        // 这里可以添加跳转到登录页的逻辑
      } else if (error.response?.status === 404) {
        ElMessage.error('文件不存在')
      }
    }
  }
}
//文件删除
const deleteFile = async (data:any)=>{
  console.log(data);
  const file  = ref(data);

 await reDleteFile(file.value);

 
 getFilelist();
}

const getFilelist = async ()=>{
 let res =  await reFileList()

 fileslists.value = res.data;
}

onMounted(()=>{
  getFilelist()
})
</script>

<style scoped>
.upload-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}
</style>